const Base = require('./base.js');
const moment = require('moment');
module.exports = class extends Base {
    async indexAction() {
        const model = this.model('goods');
        const idList = await this.model('goods_integral').where({is_delete:0}).getField('distinct goods_id');
        const goodsList = await model.where({id:['in',idList]}).select();
        for(const item of goodsList){
            item.req_points= await model.getIntegral(item.id);
        }
        return this.success(goodsList);
    }
    /**
     * 商品详情页数据
     * @returns {Promise.<Promise|PreventPromise|void>}
     */
    async detailAction() {
        const goodsId = this.get('id');
        const model = this.model('goods');
        let info = await model.where({
            id: goodsId,
			is_delete:0
        }).find();
		if(think.isEmpty(info)){
			return this.fail('该商品不存在或已下架');
        }
        info.req_points= await model.getIntegral(info.id);
        const gallery = await this.model('goods_gallery').where({
            goods_id: goodsId,
            is_delete: 0,
        }).order('sort_order').limit(6).select();
        // await this.model('footprint').addFootprint(think.userId, goodsId);
        let productList = await model.getProductIntegral(goodsId);
        let goodsNumber = 0;
        for (const item of productList) {
            if (item.goods_number > 0) {
                goodsNumber = goodsNumber + item.goods_number;
            }
        }
        let specificationList = await model.getIntegralList(goodsId);
        info.goods_number = goodsNumber;
        return this.success({
            info: info,
            gallery: gallery,
            specificationList: specificationList,
            productList: productList
        });
    }
    async goodsShareAction() {
        const goodsId = this.get('id');
        const info = await this.model('goods').where({
            id: goodsId
        }).field('name,retail_price').find();
        info.req_points= await model.getIntegral(info.id);
        return this.success(info);
    }
    /**
     * 获取商品列表
     * @returns {Promise.<*>}
     */
    async listAction() {
        const keyword = this.get('keyword');
        const sort = this.get('sort');
        const order = this.get('order');
        const sales = this.get('sales');
        const model = this.model('goods');
        const idList = await this.model('goods_integral').where({is_delete:0}).getField('distinct goods_id');
        const whereMap = {
            is_on_sale: 1,
            is_delete: 0,
            id:['in',idList]
        };
        if (!think.isEmpty(keyword)) {
            whereMap.name = ['like', `%${keyword}%`];
            // 添加到搜索历史
            await this.model('search_history').add({
                keyword: keyword,
                user_id: think.userId,
                add_time: parseInt(new Date().getTime() / 1000)
            });
            //    TODO 之后要做个判断，这个词在搜索记录中的次数，如果大于某个值，则将他存入keyword
        }
        // 排序
        let orderMap = {};
        if (sort === 'price') {
            // 按价格
            orderMap = {
                retail_price: order
            };
        } else if (sort === 'sales') {
            // 按价格
            orderMap = {
                sell_volume: sales
            };
        } else {
            // 按商品添加时间
            orderMap = {
                sort_order: 'asc'
            };
        }
        const goodsData = await model.where(whereMap).order(orderMap).select();
        for(const item of goodsData){
            item.req_points= await model.getIntegral(item.id);
        }
        return this.success(goodsData);
    }
    /**
     * 在售的商品总数
     * @returns {Promise.<Promise|PreventPromise|void>}
     */
    async countAction() {
        const goodsCount = await this.model('goods_integral').where({
            id:['>',0]
            // is_delete: 0,
            // is_on_sale: 1
        }).count('distinct goods_id');
        return this.success({
            goodsCount: goodsCount
        });
    }


    async currentlistAction() {
        const page = this.post('page');
        const size = this.post('size');
        const categoryId = this.post('id');
        const idList = await this.model('goods_integral').where({is_delete:0}).getField('distinct goods_id');
        let list;
        if (categoryId == 0) {
             list = await this.model('goods').where({
                is_on_sale: 1,
                is_delete: 0,
                id:['in',idList]
            }).order({
                sort_order: 'asc'
            }).field('name,id,goods_brief,min_retail_price,list_pic_url,goods_number').page(page, size).countSelect();
        } else {
             list = await this.model('goods').where({
                is_on_sale: 1,
                is_delete: 0,
                category_id: categoryId,
                id:['in',idList]
            }).order({
                sort_order: 'asc'
            }).field('name,id,goods_brief,min_retail_price,list_pic_url,goods_number').page(page, size).countSelect();

        }

        for(const item of list.data){
            item.req_points= await this.model('goods').getIntegral(item.id);
        }
        return this.success(list);
    }

     /**
     * 提交订单
     * @returns {Promise.<void>}
     */
    async submitAction() {
        // 获取收货地址信息和计算运费
        const addressId = this.post('addressId');
        const offlinePay = this.post('offlinePay');
        let postscript = this.post('postscript');
        let order_type = this.post('order_type')||9;//9积分 10积分自提
        const buffer = Buffer.from(postscript); // 留言
        const checkedAddress = await this.model('address').where({
            id: addressId
        }).find();
        if (think.isEmpty(checkedAddress)&&order_type!=10) {//非自提应选择收货地址
            return this.fail('请选择收货地址');
        }
        if (think.isEmpty(checkedAddress)) {//收货地址
            checkedAddress={};
        }
        // 获取要购买的商品
        const checkedGoodsList = await this.model('cart').where({
            user_id: think.userId,
            checked: 1,
            is_delete: 0
        }).select();
        if (think.isEmpty(checkedGoodsList)) {
            return this.fail('请选择商品');
        }
        let checkPrice = 0;
        let checkStock = 0;
        let product;
        for(const item of checkedGoodsList){
            // let product = await this.model('product').where({
            //     id:item.product_id
            // }).find();
            product = await this.model('product').join({ table: 'goods_integral',  join: 'right',as:'gi',on: ['goods_specification_ids', 'spec_id'] })
            .where({'hiolabs_product.id': item.product_id,'hiolabs_product.is_delete':0})
            .field('hiolabs_product.*,gi.spec_id, gi.get_points, gi.req_points, gi.tips, gi.total, gi.limit, gi.is_delete as g_delete, gi.sort_order, gi.gettype, gi.gi_desc, gi.spare_field, gi.begin_time, gi.end_time, gi.create_time, gi.update_time').find();

            //获取总兑换数和每人兑换数
        const ucount= await this.model('order_goods').join({ table: 'order',  join: 'left',as:'go',on: ['order_id', 'id'] })
        .where({'hiolabs_order_goods.user_id': think.userId,goods_specifition_ids:product.goods_specification_ids,'go.order_type':['in',[9,10]]}).sum('number');
        const tcount= await this.model('order_goods').join({ table: 'order',  join: 'left',as:'go',on: ['order_id', 'id'] })
        .where({goods_specifition_ids:product.goods_specification_ids,'go.order_type':['in',[9,10]]}).sum('number');
            
        if(item.number+ucount > product.limit){
            return this.fail(400, '每人限制兑换 '+product.limit+',你已兑换 '+ucount);
        }
        
        if(item.number+tcount > product.total){
            return this.fail(400, '共可领取 '+product.total+',已领 '+tcount);
        }

            if(item.number > product.goods_number){
                checkStock++;
            }
            if(item.retail_price != item.add_price){
                checkPrice++;
            }
        }
        

        if(checkStock > 0){
            return this.fail(400, '库存不足，请重新下单');
        }
        if(checkPrice > 0){
            return this.fail(400, '价格发生变化，请重新下单');
        }
        // 获取订单使用的红包
        // 如果有用红包，则将红包的数量减少，当减到0时，将该条红包删除
        // 统计商品总价
        let goodsTotalPrice = 0;
        for (const cartItem of checkedGoodsList) {
            goodsTotalPrice += cartItem.number * cartItem.retail_price;
        }
        // 订单价格计算
        const orderTotalPrice = goodsTotalPrice; // 订单的总价
        const actualPrice = orderTotalPrice - 0; // 减去其它支付的金额后，要实际支付的金额 比如满减等优惠
        const currentTime = parseInt(new Date().getTime() / 1000);
        let userInfo = await this.model('user').where({
            id: think.userId
        }).find();
        if(actualPrice>userInfo.integral){
            return this.fail(400, '你的积分不足，兑换失败');
        }
        let print_info = '';
        for (const item in checkedGoodsList) {
            let i = Number(item) + 1;
            print_info = print_info + i + '、' + checkedGoodsList[item].goods_aka + '【' + checkedGoodsList[item].number + '】 ';
        }
        let def = await this.model('settings').where({
            id: 1
        }).find();
        let sender_name = def.Name;
        let sender_mobile = def.Tel;
        // let sender_address = '';
        // const checkedAddress = await this.model('address').where({id: addressId}).find();
        const orderInfo = {
            order_sn: this.model('order').generateOrderNumber(),
            user_id: think.userId,
            // 收货地址和运费
            consignee: checkedAddress.name,
            mobile: checkedAddress.mobile,
            province: checkedAddress.province_id,
            city: checkedAddress.city_id,
            district: checkedAddress.district_id,
            address: checkedAddress.address,
            order_status: 300, // 订单初始状态为 101,300待发货
            // 根据城市得到运费，这里需要建立表：所在城市的具体运费
            postscript: buffer.toString('base64'),
            add_time: currentTime,
            goods_price: goodsTotalPrice,
            order_price: orderTotalPrice,
            actual_price: actualPrice,
            change_price: actualPrice,
            print_info: print_info,
            offline_pay:offlinePay,
            order_type:order_type
        };
        // 开启事务，插入订单信息和订单商品
        const orderId = await this.model('order').add(orderInfo);
        orderInfo.id = orderId;
        if (!orderId) {
            return this.fail('订单提交失败');
        }
        // 将商品信息录入数据库
        const orderGoodsData = [];
        const integralData = [];
        for (const goodsItem of checkedGoodsList) {
            orderGoodsData.push({
                user_id: think.userId,
                order_id: orderId,
                goods_id: goodsItem.goods_id,
                product_id: goodsItem.product_id,
                goods_name: goodsItem.goods_name,
                goods_aka: goodsItem.goods_aka,
                list_pic_url: goodsItem.list_pic_url,
                retail_price: goodsItem.retail_price,
                number: goodsItem.number,
                goods_specifition_name_value: goodsItem.goods_specifition_name_value,
                goods_specifition_ids: goodsItem.goods_specifition_ids
            });
            integralData.push({
                user_id: think.userId,
                order_id: orderId,
                integral:goodsItem.retail_price*goodsItem.number*-1,
                reason:'兑换积分商品',
                is_finish:1
            })
        }
        await this.model('order_goods').addMany(orderGoodsData);
        await this.model('task_integral').addMany(integralData);
        await this.model('user').where({id: think.userId}).decrement('integral',actualPrice);
        await this.model('cart').clearBuyGoods();
        return this.success({
            orderInfo: orderInfo
        });
    }


};